<template>
  <div class="user-profile-container">
    <div class="page-header">
      <div class="page-title">个人中心</div>
    </div>
    
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
        <el-card shadow="hover" class="profile-card">
          <!-- 头像展示区域 -->
          <div class="avatar-container">
            <div class="avatar-wrapper">
              <div v-if="userInfo.avatar" class="avatar-display">
                <!-- 显示调试信息 -->
                <div v-if="avatarLoadError" class="debug-info">
                  <div>原始URL: {{ userInfo.avatar }}</div>
                  <div>处理后URL: {{ getFullAvatarUrl(userInfo.avatar) }}</div>
                </div>
                
                <el-image
                  :src="getFullAvatarUrl(userInfo.avatar)"
                  class="user-avatar"
                  fit="contain"
                  :preview-src-list="[getFullAvatarUrl(userInfo.avatar)]"
                  @error="handleAvatarLoadError"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><icon-picture /></el-icon>
                      <div>头像加载失败</div>
                      <el-button size="small" @click="retryLoadAvatar">重试</el-button>
                    </div>
                  </template>
                </el-image>
              </div>
              <el-avatar
                v-else
                :size="100"
                :src="defaultAvatar"
                @error="avatarLoadError = true"
              />
            </div>
            <div class="avatar-actions">
              <el-upload
                class="upload-avatar"
                :action="''"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleAvatarChange"
                :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/png,image/gif"
              >
                <el-button size="small" type="primary">更换头像</el-button>
              </el-upload>
              <el-button 
                v-if="userInfo.avatar" 
                size="small" 
                type="danger" 
                @click="handleDeleteAvatar"
              >
                删除头像
              </el-button>
            </div>
          </div>
          
          <div class="info-item">
            <div class="label">用户名</div>
            <div class="value">{{ userInfo.username }}</div>
          </div>
          
          <div class="info-item">
            <div class="label">角色</div>
            <div class="value">
              <el-tag :type="getRoleTagType(userInfo.role)">
                {{ getRoleName(userInfo.role) }}
              </el-tag>
            </div>
          </div>
          
          <div class="info-item">
            <div class="label">部门</div>
            <div class="value">{{ getDepartmentName(userInfo.department) }}</div>
          </div>
          
          <div class="info-item">
            <div class="label">最近登录</div>
            <div class="value">
              <el-tooltip
                :content="formatTime(userInfo.last_login)"
                placement="top"
                :disabled="!userInfo.last_login"
              >
                <span>{{ formatTimeRelative(userInfo.last_login) }}</span>
              </el-tooltip>
            </div>
          </div>
          
          <div class="info-item">
            <div class="label">注册时间</div>
            <div class="value">{{ formatTime(userInfo.created_at) }}</div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧个人信息编辑表单 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            :disabled="!isEditing"
          >
            <el-form-item label="姓名" prop="fullName">
              <el-input v-model="profileForm.fullName" placeholder="请输入姓名" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-form-item label="部门" prop="department">
              <el-select v-model="profileForm.department" placeholder="请选择部门" style="width: 100%">
                <el-option label="营销部" value="marketing"></el-option>
                <el-option label="客服部" value="customer_service"></el-option>
                <el-option label="技术部" value="technology"></el-option>
                <el-option label="财务部" value="finance"></el-option>
                <el-option label="人力资源部" value="hr"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button v-if="!isEditing" type="primary" @click="startEditing">编辑信息</el-button>
              <template v-else>
                <el-button type="primary" @click="updateProfile">保存</el-button>
                <el-button @click="cancelEditing">取消</el-button>
              </template>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 修改密码卡片 -->
        <el-card shadow="hover" class="mt-20">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="140px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { getProfile, updateProfile as apiUpdateProfile, changePassword as apiChangePassword } from '@/api/modules/auth'
import { deleteAvatar } from '@/api/modules/avatar'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { formatDateTime, formatRelativeTime } from '@/utils/format'

const userStore = useUserStore()
const defaultAvatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
const avatarLoadError = ref(false)

// 用户信息
const userInfo = ref({})
const isEditing = ref(false)
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 个人信息表单
const profileForm = reactive({
  fullName: '',
  email: '',
  department: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserProfile = async () => {
  try {
    const response = await getProfile()
    if (response.success && response.data) {
      // 确保头像URL是完整路径
      if (response.data.avatar) {
        response.data.avatar = getFullAvatarUrl(response.data.avatar);
      }
      
      userInfo.value = response.data
      
      console.log('用户信息:', userInfo.value);
      console.log('头像URL:', userInfo.value.avatar);
      
      // 填充表单
      profileForm.fullName = response.data.full_name || ''
      profileForm.email = response.data.email || ''
      profileForm.department = response.data.department || ''
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请刷新页面重试')
  }
}

// 开始编辑
const startEditing = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  profileForm.fullName = userInfo.value.full_name || ''
  profileForm.email = userInfo.value.email || ''
  profileForm.department = userInfo.value.department || ''
  isEditing.value = false
}

// 更新个人信息
const updateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    
    const response = await apiUpdateProfile({
      full_name: profileForm.fullName,
      email: profileForm.email,
      department: profileForm.department
    })
    
    if (response.success) {
      ElMessage.success('个人信息更新成功')
      fetchUserProfile()
      isEditing.value = false
      
      // 更新全局用户状态
      userStore.userInfo = {
        ...userStore.userInfo,
        full_name: profileForm.fullName,
        email: profileForm.email,
        department: profileForm.department
      }
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败，请重试')
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    const response = await apiChangePassword({
      old_password: passwordForm.oldPassword,
      new_password: passwordForm.newPassword
    })
    
    if (response.success) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请重试')
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  const isAllowedType = allowedTypes.includes(file.type);

  if (!isAllowedType) {
    ElMessage.error('头像只能是JPG/PNG图片或GIF动图!');
    return false;
  }
  
  return true;
}

// 头像文件改变时处理
const handleAvatarChange = async (file) => {
  if (!file) return;
  
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error('头像只能是JPG/PNG图片或GIF动图!');
    return;
  }
  
  try {
    // 创建FormData
    const formData = new FormData();
    formData.append('avatar', file.raw);
    
    // 使用API方法上传
    const { uploadAvatar } = await import('@/api/modules/avatar');
    const response = await uploadAvatar(formData);
    
    console.log('上传头像响应:', response);
    
    // 处理上传结果
    if (response.success) {
      // 检查URL路径
      let avatarUrl = '';
      
      if (response.data && response.data.avatar_url) {
        avatarUrl = response.data.avatar_url;
        console.log('服务器返回头像URL:', avatarUrl);
      } else if (response.data && response.data.avatar_path) {
        // 如果只有路径没有完整URL，则构建URL
        avatarUrl = getFullAvatarUrl(response.data.avatar_path);
        console.log('根据路径构建URL:', avatarUrl);
      } else {
        // 兜底方案，使用文件名构建URL
        const filename = file.raw.name || `${Date.now()}.png`;
        avatarUrl = `/media/avatars/${filename}`;
        console.log('使用兜底URL:', avatarUrl);
      }
      
      // 更新用户信息对象
      userInfo.value = {
        ...userInfo.value,
        avatar: avatarUrl
      };
      
      // 更新全局用户状态
      // 首先确保userStore.userInfo存在
      if (userStore.userInfo) {
      userStore.userInfo = {
        ...userStore.userInfo,
        avatar: avatarUrl
      };
        // 重新存储到本地存储中
        const { setUserInfo } = await import('@/utils/auth');
        setUserInfo(userStore.userInfo);
      }
      
      // 直接更新Pinia存储中的头像路径
      userStore.$patch({ userInfo: { avatar: avatarUrl } });
      
      ElMessage.success('头像上传成功');
    } else {
      ElMessage.error(response.message || '头像上传失败');
    }
  } catch (error) {
    console.error('上传头像出错:', error);
    ElMessage.error('头像上传失败，请重试');
  }
}

// 删除头像
const handleDeleteAvatar = async () => {
  try {
    const response = await deleteAvatar()
    
    if (response.success) {
      userInfo.value.avatar = null
      
      // 更新全局用户状态
      // 首先确保userStore.userInfo存在
      if (userStore.userInfo) {
      userStore.userInfo = {
        ...userStore.userInfo,
        avatar: null
        };
        // 重新存储到本地存储中
        const { setUserInfo } = await import('@/utils/auth');
        setUserInfo(userStore.userInfo);
      }
      
      // 直接更新Pinia存储中的头像路径
      userStore.$patch({ userInfo: { avatar: null } });
      
      ElMessage.success('头像删除成功')
    } else {
      ElMessage.error(response.message || '头像删除失败')
    }
  } catch (error) {
    console.error('删除头像失败:', error)
    ElMessage.error('删除头像失败，请重试')
  }
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    'admin': 'danger',
    'analyst': 'warning',
    'manager': 'success',
    'marketing': 'info',
    'dept_head': 'primary',
    'executive': 'danger'
  }
  return types[role] || ''
}

// 获取角色名称
const getRoleName = (role) => {
  const roles = {
    'admin': '管理员',
    'analyst': '数据分析师',
    'manager': '客户经理',
    'marketing': '营销专员',
    'dept_head': '部门主管',
    'executive': '高管'
  }
  return roles[role] || role
}

// 获取部门名称
const getDepartmentName = (departmentCode) => {
  const departments = {
    'marketing': '营销部',
    'customer_service': '客服部',
    'technology': '技术部',
    'finance': '财务部',
    'hr': '人力资源部'
  }
  return departments[departmentCode] || departmentCode
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return formatDateTime(time)
}

// 添加一个额外的函数用于显示相对时间
const formatTimeRelative = (time) => {
  if (!time) return '-'
  return formatRelativeTime(time)
}

// 处理头像URL，确保是完整的URL
const getFullAvatarUrl = (url) => {
  if (!url) return null;
  
  // 如果已经是绝对URL（包含http://或https://），则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    console.log(`使用绝对URL: ${url}`);
    return url;
  }
  
  // 构建完整URL - 使用与后端相同的协议和域名
  const protocol = window.location.protocol;
  const host = 'localhost:8000'; // 后端服务器地址
  
  // 如果以/media/开头
  if (url.startsWith('/media/')) {
    const fullUrl = `${protocol}//${host}${url}`;
    console.log(`使用/media/路径构建完整URL: ${fullUrl}`);
    return fullUrl;
  }
  
  // 如果只有文件名，则添加/media/avatars/前缀
  if (!url.includes('/')) {
    const fullUrl = `${protocol}//${host}/media/avatars/${url}`;
    console.log(`构建完整URL: ${fullUrl}`);
    return fullUrl;
  }
  
  // 其他情况，添加/media/前缀
  const fullUrl = url.startsWith('/') ? `${protocol}//${host}${url}` : `${protocol}//${host}/media/${url}`;
  console.log(`构建媒体URL: ${fullUrl}`);
  return fullUrl;
}

// 处理头像加载失败
const handleAvatarLoadError = () => {
  avatarLoadError.value = true;
  console.warn('头像加载失败，尝试重试...');
}

// 重试加载头像
const retryLoadAvatar = () => {
  avatarLoadError.value = false; // 重置错误状态
  console.log('尝试重新加载头像...');
  // 重新渲染或更新头像元素，使其重新尝试加载
  // 在Vue中，通常需要使用v-if或v-show来控制头像的显示/隐藏
  // 这里我们直接重新设置userInfo.avatar，Vue会自动更新头像
  userInfo.value.avatar = getFullAvatarUrl(userInfo.value.avatar);
  console.log('头像URL已更新为:', userInfo.value.avatar);
}

// 生命周期钩子
onMounted(() => {
  fetchUserProfile()
})
</script>

<style lang="scss" scoped>
.user-profile-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .profile-card {
    margin-bottom: 20px;
    
    .avatar-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px 0;
      border-bottom: 1px solid #eee;
      
      .avatar-wrapper {
        width: 150px; 
        height: 150px;
        margin-bottom: 15px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #eaeaea;
        background-color: #f8f8f8;

        .avatar-display {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          position: relative;
        }

        .debug-info {
          position: absolute;
          top: 0;
          left: 0;
          background: rgba(0, 0, 0, 0.7);
          color: #fff;
          padding: 8px;
          font-size: 10px;
          width: 100%;
          z-index: 10;
          word-break: break-all;
        }

        .user-avatar {
          max-width: 100%;
          max-height: 100%;
        }

        .image-error {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          color: #909399;
          padding: 10px;
          width: 100%;
          height: 100%;
          
          .el-icon {
            font-size: 32px;
            margin-bottom: 8px;
          }
          
          button {
            margin-top: 8px;
          }
        }
      }
      
      .avatar-actions {
        margin-top: 15px;
        display: flex;
        gap: 10px;
      }
    }
    
    .info-item {
      padding: 12px 0;
      display: flex;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        width: 80px;
        color: #909399;
      }
      
      .value {
        flex: 1;
        color: #303133;
      }
    }
  }
  
  .card-header {
    font-weight: bold;
  }
  
  .mt-20 {
    margin-top: 20px;
  }
}
</style>